<template>
  <div class="content-area">
    <el-container class="container-style">
      <el-container>
        <div style="width: 96%; margin: 0px auto; display: flex; flex-direction: column; align-items: center;">
          <div style="display: flex; align-items: center;">
            <h2>楼栋管理</h2>
          </div>

          <div style="background-color: white; padding: 20px; margin-top: 10px; width: 100%">
            <div class="table-header-container">
              <div class="search-container">
                <el-select v-model="searchOption" placeholder="请选择查询方式" class="search-select">
                  <el-option label="按小区 ID 查询" value="communityId"></el-option>
                  <el-option label="按楼栋编号查询" value="buildingNumber"></el-option>
                </el-select>
                <el-input v-model="searchQuery" placeholder="请输入查询关键词" class="search-input"></el-input>
                <el-button type="primary" @click="searchBuilding" class="search-button">查询</el-button>
              </div>
              <el-button type="primary" @click="addDialogFormVisible = true">增加记录</el-button>
            </div>
            <table v-if="buildingForm && buildingForm.data && buildingForm.data.records"
                   style="text-align: center; width: 100%; border-collapse: collapse;">
              <thead>
              <tr style="border: 1px solid #eee;">
                <th style="width: 50px;  border: 1px solid #eee;">楼栋id</th>
                <th style="width: 80px;  border: 1px solid #eee;">所属小区id</th>
                <th style="width: 80px;  border: 1px solid #eee;">楼栋编号</th>
                <th style="width: 60px;  border: 1px solid #eee;">楼栋单元号</th>
                <th style="width: 60px;  border: 1px solid #eee;">楼栋楼层数</th>
                <th style="width: 150px;  border: 1px solid #eee;">楼栋位置</th>
                <th style="width: 80px;  border: 1px solid #eee;">楼栋户型</th>
                <th style="width: 80px;  border: 1px solid #eee;">楼栋户数</th>
                <th style="width: 80px;  border: 1px solid #eee;">操作</th>
              </tr>
              </thead>
              <tbody>
              <tr v-for="(item, index) in buildingForm.data.records" :key="index" style="border: 1px solid #eee;">
                <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.id" disabled class="disabled-style"></el-input>
                </td>
                <td style="width: 80px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.communityId" disabled class="disabled-style"></el-input>
                </td>
                <td style="width: 80px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.buildingNumber" :disabled="!item.isEdit" :class="{
        'normal-input-color':!isEdit,
        'edit-input-color': isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 60px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.buildingUnit" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 60px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.floorCount" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 150px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.location" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 80px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.houseType" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.households" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
                </td>
                <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                  <div class="button-group">
                    <template v-if="!item.isEdit">
                      <el-button type="success" @click="saveItem(item)">修改记录</el-button>
                      <el-button type="danger" @click="openDeleteDialog(item.id)">删除记录</el-button>
                    </template>
                    <template v-if="item.isEdit&&buildingForm && buildingForm.data && buildingForm.data.records.some(item => item.isEdit)">
                      <el-button type="success" @click="handleSaveEdit">保存修改</el-button>
                      <el-button type="default"  @click="handleCancelEdit" style="margin-left: 10px">取消修改</el-button>
                    </template>
                  </div>
                </td>
              </tr>
              </tbody>
            </table>
            <div v-else-if="errorMessage">{{ errorMessage }}</div>
          </div>
          <div style="display: flex; justify-content: center; width: 100%;">
            <el-pagination
                class="footer"
                v-if="buildingForm && buildingForm.data"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[8, 10, 12]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="buildingForm.data.total"
            >
            </el-pagination>
          </div>
        </div>
      </el-container>
    </el-container>
    <el-dialog v-model="addDialogFormVisible" title="增加楼栋" width="500">
      <el-form :model="addForm">
        <el-form-item label="楼栋所属小区id" :label-width="formLabelWidth">
          <el-input v-model="addForm.communityId" placeholder="请输入楼栋所属小区id" />
        </el-form-item>
        <el-form-item label="楼栋编号" :label-width="formLabelWidth">
          <el-input v-model="addForm.buildingNumber" placeholder="请输入楼栋编号" />
        </el-form-item>
        <el-form-item label="楼栋单元号" :label-width="formLabelWidth">
          <el-input v-model="addForm.buildingUnit" placeholder="请输入楼栋单元号"/>
        </el-form-item>
        <el-form-item label="楼栋楼层数" :label-width="formLabelWidth">
          <el-input v-model="addForm.floorCount" placeholder="请输入楼栋楼层数" />
        </el-form-item>
        <el-form-item label="楼栋位置" :label-width="formLabelWidth">
          <el-input v-model="addForm.location" placeholder="请输入楼栋位置" />
        </el-form-item>
        <el-form-item label="楼栋户型" :label-width="formLabelWidth">
          <el-input v-model="addForm.houseType" placeholder="请输入楼栋户型" />
        </el-form-item>
        <el-form-item label="楼栋户数" :label-width="formLabelWidth">
          <el-input v-model="addForm.households" placeholder="请输入楼栋户数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleConfirm">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="deleteDialogFormVisible" title="删除楼栋" width="500">
      确定删除该楼栋信息？
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleDelete">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>



<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

export default {
  data() {
    return {
      errorMessage: '',
      currentPage: 1,
      pageSize: 12,
      addDialogFormVisible: false,
      addForm: {
        communityId: "",
        buildingNumber: "",
        buildingUnit: "",
        floorCount: "",
        location: "",
        houseType: "",
        households: ""
      },
      buildingForm: {
        id: "",
        communityId: "",
        buildingNumber: "",
        buildingUnit: "",
        floorCount: "",
        location: "",
        houseType: "",
        households: ""
      },
      isEdit: false,
      saveEditId: null,
      originalInfo: null,
      searchQuery: '',
      deleteId: null,
      deleteDialogFormVisible: false,
      formLabelWidth: '120px',
      searchOption: '',
    };
  },
  setup() {
    const router = useRouter();
    return {
      router
    };
  },
  methods: {
    async fetchData() {
      try {
        const token = localStorage.getItem('token');
        let url = '/api/buildings/page';
        let params = {
          current: this.currentPage,
          size: this.pageSize
        };
        if (this.searchOption =='communityId') {
          params.communityId = this.searchQuery;
        }else if(this.searchOption == 'buildingNumber'){
          params.buildingNumber = this.searchQuery;
        }
        const response = await axios.get(url, {
          headers: {
            Authorization: token
          },
          params: params
        });
          this.buildingForm.data = response.data;
          this.originalInfo = {...this.buildingForm };
          if (this.buildingForm && this.buildingForm.data && this.buildingForm.data.records) {
            this.buildingForm.data.records.forEach(item => {
              item.isEdit = false;
            });
          }
        console.log('buildingForm:', this.buildingForm);
      } catch (error) {
        ElMessage.error('获取楼栋列表数据统计失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    handleConfirm() {
      this.confirmAdd();
    },
    async confirmAdd() {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.post('/api/buildings',null,{
          headers: {
            Authorization: token
          },
          params:{
            communityId: this.addForm.communityId,
            buildingNumber: this.addForm.buildingNumber,
            buildingUnit: this.addForm.buildingUnit,
            floorCount: this.addForm.floorCount,
            location: this.addForm.location,
            houseType: this.addForm.houseType,
            households: this.addForm.households
          }
        });
        if (response.data.code === 200) {
          ElMessage.success('增加楼栋记录成功');
        } else {
          ElMessage.error('增加楼栋记录失败,请输入正确信息');
        }
        this.addDialogFormVisible = false;
        this.fetchData();
      } catch (error) {
        ElMessage.error('增加楼栋记录时出错：' + error.message);
      }
    },
    saveItem(item) {
      item.isEdit = true;
      this.saveEditId = item.id;
    },
    async handleSaveEdit() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          throw new Error('token不存在');
        }
        const currentEditedItem = this.buildingForm.data.records.find(
            item => item.id === this.saveEditId
        );
        if (!currentEditedItem) {
          ElMessage.error('未找到当前编辑的楼栋记录');
          return;
        }
        const response = await axios.put(
            `/api/buildings/${this.saveEditId}`,
            null,
            {
              headers: {
                Authorization: token
              },
              params:{
                buildingId: currentEditedItem.buildingId,
                communityId: currentEditedItem.communityId,
                buildingNumber: currentEditedItem.buildingNumber,
                buildingUnit: currentEditedItem.buildingUnit,
                floorCount: currentEditedItem.floorCount,
                location: currentEditedItem.location,
                houseType: currentEditedItem.houseType,
                households: currentEditedItem.households
              }
            }
        );
        if (response.data.code === 200) {
          this.fetchData();
          this.isEdit = false;
          ElMessage.success('楼栋信息修改成功');
        } else {
          ElMessage.error('楼栋信息修改失败，请输入正确信息');
        }
      } catch (error) {
        ElMessage.error('楼栋信息修改时出错：' + error.message);
      }
    },
    handleCancelEdit() {
      this.buildingForm = {...this.originalInfo };
      if (this.buildingForm && this.buildingForm.data && this.buildingForm.data.records) {
        this.buildingForm.data.records.forEach(item => {
          item.isEdit = false;
        });
      }
      this.isEdit = false;
    },
    async searchBuilding() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
        if (this.searchOption === 'communityId') {
          const response = await axios.get('/api/buildings/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.searchQuery
            }
          });
          if (response.data.records.length > 0) {
            this.buildingForm.data = response.data;
            this.originalInfo = {...this.buildingForm};
          }else{
            ElMessage.error('查询楼栋信息失败，请输入正确信息')
          }
        }  else if (this.searchOption === 'buildingNumber') {
          const response = await axios.get('/api/buildings/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              buildingNumber: this.searchQuery
            }
          });
          if (response.data.records.length > 0) {
            this.buildingForm.data = response.data;
            this.originalInfo = {...this.buildingForm};
          }else{
            ElMessage.error('查询楼栋信息失败，请输入正确信息')
          }
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    },
    openDeleteDialog(id){
      this.deleteId=id;
      this.deleteDialogFormVisible=true;
    },
    async handleDelete(){
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
        const response = await axios.delete(`/api/buildings/${this.deleteId}`, {
          headers: {
            Authorization: token
          }
        });
        if (response.data.code === 200) {
          ElMessage.success("删除成功");
          this.fetchData();
          this.deleteDialogFormVisible=false;
        } else {
          ElMessage.error('删除楼栋信息失败');
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    }
  },
  mounted() {
    this.fetchData();
  }
};
</script>

<style scoped>
.search-container {
  display: flex;
  align-items: center; /* 使子元素在垂直方向上居中对齐 */
  gap: 5px; /* 设置子元素之间的间距 */
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.search-input {
  flex: 1;
  width: 300px;
  margin-right: 10px;
}

.search-select {
  flex: 1;
  width: 30px;
}

.search-button {
  min-width: 80px;
}

.footer {
  margin-top: 20px;
  text-align: center;
  padding: 10px;
  transition: margin-left 0.3s;
}

.container-style {
  height: 100%;
}

.content-area {
  background-color: #f2f5fa;
  padding: 20px;
  height: calc(100vh - 120px); /* 50(header) + 10(footer padding top) + 60(footer height & bottom margin) */
  overflow-y: auto; /* 启用滚动条 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.search-input {
  flex: 1;
  width: 250px;
  margin-right: 10px;
}

.search-button {
  min-width: 80px;
}

.table-header-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.disabled-style {
  cursor: default;
}


.form-label-width {
  width: 120px;
}

.normal-input-color {
  color: inherit;
}

.edit-input-color {
  color: #ccc;
}

.community-select-wrapper {
  display: flex;
  align-items: center;
}

.content-area {
  background-color: #f2f5fa;
  padding: 20px;
  height: calc(100vh - 120px); /* 50(header) + 10(footer padding top) + 60(footer height & bottom margin) */
  overflow-y: auto; /* 启用滚动条 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}
</style>